﻿/***************************************
= Global
-------------------------------------- */
var Global = { PageIndex: 1, PageSize: 12, SiteUrl: 'http://ktm.vn' };


/***************************************
= Product
-------------------------------------- */
function filterProduct(pageIndex, pageSize) {

    var lstCategory = jQuery('#hfLstCategory').val();

    var lstPropertyValue = '';
    jQuery('.lstPropertyValue').each(function () {
        if ($(this).checked == true) {
            lstPropertyValue += jQuery(this).val() + ', ';
        }
    });

    if (lstPropertyValue.length > 0)
        lstPropertyValue = lstPropertyValue.substr(0, lstPropertyValue.length - 2);

    console.log('C: ' + lstCategory);
    console.log('PV: ' + lstPropertyValue);

    var orderBy = 'UnitPrice';

    var params = { };
    params['catId'] = lstCategory;
    params['pvId'] = lstPropertyValue;
    params['orderBy'] = orderBy;
    params['pi'] = pageIndex;
    params['ps'] = pageSize;
        
    jQuery.ajax({
        url: '/Ajax/Product/ListProductFilter.aspx',
        data: params,
        type: 'get',
        success: function (result) {
            if (result.length > 0)
                jQuery('#filterProduct').html(result);
        }
    });        
}

/***************************************
= Cart
-------------------------------------- */
function addToCart(pId) {
    var url = String.format('/Handlers/SiteHandler.ashx?command=addtocart&id={0}', pId);
    $.post(url, function (data) {
        if (data == "success")
            window.location.href = Global.SiteUrl + "/gio-hang.htm";
        else
            alert("Không thêm được vào giỏ hàng. Vui lòng quay lại sau!");
    });
}

/***************************************
= Comment & Related Product
-------------------------------------- */
function listComment(id, typeId, pageIndex) {
    var url = String.format('/Ajax/Comment/ListCommentByIdTypeId.aspx?id={0}&tId={1}&pi={2}', id, typeId, pageIndex);    
    $.ajax({
        url: url,
        data: {},
        type: 'get',
        success: function (result) {
            if (result.length > 0)
                $('#list-comment').html(result);
        }
    });
}

function listRelatedProduct(catId, pId, typeId, pageIndex) {
    var url = String.format('/Ajax/Product/ListPaginationRelatedProduct.aspx?catId={0}&pId={1}&tId={2}&pi={3}', catId, pId, typeId, pageIndex);    
    $.ajax({
        url: url,
        data: {},
        type: 'get',
        success: function (result) {
            if (result.length > 0)
                $('#list-related-product').html(result);
        }
    });
}

function postComment(pId, tId) {
    var fullName = $('#txtFullName').val();
    var email = $('#txtEmail').val();
    var content = $('#txtBody').val();

    var url = String.format('/Handlers/SiteHandler.ashx?command=postComment&id={0}&tId={1}&fn={2}&email={3}&content={4}', pId, tId, fullName, email, content);
    $.post(url, function (data) {
        if (data == "success")
            $('#commentMessage').html('<div class="nNote nSuccess hideit"><p>Bình luận của bạn đã được gửi thành công.</p></div>');
        else
            $('#commentMessage').html('<div class=\"nNote nFailure hideit\"><p>Vui lòng gửi bình luận sau.</p></div>');
    });
}

/***************************************
= Format DateTime JSON
-------------------------------------- */
function formatJsonDateTime(dateTime) {
    var d = new Date(parseInt(dateTime.substr(6)));
    var validDateTime = String.format("{0}:{1} {2}/{3}/{4}", d.getHours(), d.getMinutes(), d.getDay(), d.getMonth(), d.getFullYear());
    return validDateTime;
}

/***************************************
= Remove Sign
-------------------------------------- */
//#region
function removeSign(str) {
    str = str.toLowerCase();
    str = str.replace(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/g, "a");
    str = str.replace(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/g, "e");
    str = str.replace(/ì|í|ị|ỉ|ĩ/g, "i");
    str = str.replace(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/g, "o");
    str = str.replace(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/g, "u");
    str = str.replace(/ỳ|ý|ỵ|ỷ|ỹ/g, "y");
    str = str.replace(/đ/g, "d");
    str = str.replace(/!|@|%|\^|\*|\(|\)|\+|\=|\<|\>|\?|\/|,|\.|\:|\;|\'| |\"|\&|\#|\[|\]|~|$|_/g, "-");

    /* tìm và thay thế các kí tự đặc biệt trong chuỗi sang kí tự - */
    str = str.replace(/-+-/g, "-"); //thay thế 2- thành 1-     
    str = str.replace(/^\-+|\-+$/g, "");

    //cắt bỏ ký tự - ở đầu và cuối chuỗi  
    return str;
}
//#endregion

/***************************************
= Cut String
-------------------------------------- */
function cutStrExper(head, length) {
    if (head == "?") {
        return "";
    }
    var strLen = head.length;
    if (strLen > length) {
        head = head.substr(0, length + 5);
        var lastIndexOfSpace = head.lastIndexOf(' ');
        if (lastIndexOfSpace > 0) {
            head = head.substr(0, lastIndexOfSpace);
        }
        else {
            head = head.substr(0, length);
        }

        return head + " ...";
    }
    else {
        return head;
    }
}

/***************************************
= String Format
-------------------------------------- */
//#region
String.format = function (text) {
    //check if there are two arguments in the arguments list
    if (arguments.length <= 1) {
        //if there are not 2 or more arguments there's nothing to replace
        //just return the original text
        return text;
    }

    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; token++) {
        //iterate through the tokens and replace their placeholders from the original text in order
        text = text.replace(new RegExp("\\{" + token + "\\}", "gi"),
                                                arguments[token + 1]);
    }
    return text;
};
//#endregion

/***************************************
= Replace All
-------------------------------------- */
// Replaces all instances of the given substring.
String.prototype.replaceAll = function(
    strTarget, // The substring you want to replace
    strSubString // The string you want to replace in.
) {
    var strText = this;
    var intIndexOfMatch = strText.indexOf(strTarget);

    // Keep looping while an instance of the target string
    // still exists in the string.
    while (intIndexOfMatch != -1) {
        // Relace out the current instance.
        strText = strText.replace(strTarget, strSubString);

        // Get the index of any next matching substring.
        intIndexOfMatch = strText.indexOf(strTarget);
    }

    // Return the updated string with ALL the target strings
    // replaced out with the new substring.
    return (strText);
};
